######################################################################
# Affymetrics (RAW) data subclass for the Data object
# (to sit inside <EP::Common::DBI::Dataset>)
######################################################################
package EP::Core::Dataset::Data::affy;

use strict;
use base 'EP::Core::Dataset::Data';

use EP::Config;
use EP::Common;
use EP::Common::General;
use EP::Common::Error qw ( :try );

use EP::Common::DBI::Dataset_Metadata;
use EP::Common::DBI::Dataset_Metadata_Type;

use File::Temp;
use File::Basename;
use Tie::IxHash;

use EP::Rclient;

sub process_metadata
    {
    my $self = shift;

    my ($session) = @_;

    my $dataset_folder_path = $EP::Config::h->{EPNG_USRDATA_PATH} . "/" . $self->{owner}->folder->location;

    my $histogram_image = $self->{owner}->filename . "_histogram.png";
    my $lineplot_image = $self->{owner}->filename . "_lineplot.png";
    my $heatmap_image = $self->{owner}->filename . "_heatmap.png";
    my $legend_image = $self->{owner}->filename . "_legend.png";

    $session->status("Preparing quality control plots...") if $session;

    my $affydatafile = $dataset_folder_path . "/" . $self->{owner}->filename . ".Rdata";
    my $histpng      = $dataset_folder_path . "/" . $histogram_image;
    my $lineplotpng  = $dataset_folder_path . "/" . $lineplot_image;
    my $heatmappng   = $dataset_folder_path . "/" . $heatmap_image;
    my $legendpng    = $dataset_folder_path . "/" . $legend_image;

    # ep.affymeta returns the cdf name, number of arrays and number of genes
    my ($cdf, $arrays, $genes) = EP::Rclient->R(<<__RCODE__);
app_root = "$EP::Config::h->{ROOT}";
source("$EP::Config::h->{ROOT}/cgi-lib/tmpl/R/ep.affymeta.tmpl.R");
ep.affymeta( affydatafile = "$affydatafile"
           , histpng = "$histpng"
           , lineplotpng = "$lineplotpng"
           , heatmappng = "$heatmappng"
           , legendpng = "$legendpng"
           );
__RCODE__

    $self->update_processed_metadata(
        { mean => 'NA'
        , stdev => 'NA'
        , num_columns => $arrays
        , num_rows => $genes
        , cdf => $cdf
        , lineplot => $lineplot_image
        , heatmap   => $heatmap_image
        , histogram => $histogram_image
        , legend => $legend_image
        });

    return
        { heatmap =>
            { type => "image/png"
            , label => "Dataset heatmap"
            , value => $EP::Config::h->{EPNG_USRDATA_URL} . "/" . $self->{owner}->folder->location . "/" . $heatmap_image
            }
        , lineplot =>
            { type => "image/png"
            , label => "Dataset boxplot"
            , value => $EP::Config::h->{EPNG_USRDATA_URL} . "/" . $self->{owner}->folder->location . "/" . $lineplot_image
            }
        };
    }

# sub: rows
#   Returns the rows hash for the dataset
sub rows
    {
    my $self = shift;
    return $self->{row} if exists $self->{row};
    return $self->{row} if $self->_read_raw_data();
    die "Failed to read data!";
    }

# sub: cols
#   Returns the columns hash for the dataset
sub cols
    {
    my $self = shift;
    return $self->{column} if exists $self->{column};
    return $self->{column} if $self->_read_raw_data();
    die "Failed to read data!";
    }

# sub: _read_raw_data
# reads the affy dataset row/col annotations
sub _read_raw_data
    {
    my $self = shift;
    local ( *COLUMNS, *ROWS );

    my ($folder) = $EP::Config::h->{EPNG_USRDATA_PATH} . "/" . $self->{owner}->folder->location;
    my ($filename) = $self->{owner}->filename;

    #read the row identifiers and annotations
    open (ROWS, "$folder/$filename.rows")
        or die "Couldn't open $filename.rows, $!";

    chomp (my $row_annot_header = <ROWS>);
    my @row_annot_names = split "\t", $row_annot_header;
    shift @row_annot_names;	# shift because the first item there is "ID"

    while (<ROWS>)
        {
        chomp $_;
        my ($row_id, @row_annot) = split /\t/, $_;

        my $row_annotation = new Tie::IxHash;
        $row_annotation->Push( $row_annot_names[$_] => $row_annot[$_] ) foreach 0 .. $#row_annot_names;

        $self->{row}{$row_id} =
            { header => $row_id
            , mappped_row_header => ""
            , annot => \@row_annot
            , full_annot => $row_annotation
            };
        }
    close ROWS;

    #read the column identifiers and annotations
    open (COLUMNS, "$folder/$filename.columns")
        or die "Couldn't open $filename.columns, $!";

    chomp (my $col_annot_header = <COLUMNS>);
    my @col_annot_names = split "\t", $col_annot_header;
    shift @col_annot_names;	# shift because the first item there is "ID"

    while (<COLUMNS>)
        {
        chomp $_; 
        my ($col_id, @col_annot) = split /\t/, $_;

        my $col_annotation = new Tie::IxHash;
        $col_annotation->Push( $col_annot_names[$_] => $col_annot[$_] ) foreach 0 .. $#col_annot_names;

        $self->{column}{$col_id} =
            { header => $col_id
            , annot => \@col_annot
            , full_annot => $col_annotation
            };
        }
    close COLUMNS;
    }

1;
